<template>
  <div class="container">
    <el-row
      v-for="(item, index) in configArr"
      :key="index"
      class="tabs-item"
      :gutter="8"
    >
      <el-form ref="form" :model="item" :rules="rules" label-width="60px">
        <el-col :span="6">
          <el-form-item label="tab" prop="name">
            <el-input v-model="item.name" placeholder="请输入tab名称" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="code" prop="code">
            <el-input v-model="item.code" placeholder="请输入code属性" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="" prop="enable">
            <el-switch
              v-model="item.enable"
              active-text="启用"
              inactive-text="禁用"
            >
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col
          :class="['btn-col', activetab === index ? 'active' : '']"
          :span="6"
          v-if="addOK"
        >
          <el-button
            type="primary"
            size="small"
            @click="handlerChangeTab(index)"
            >切换</el-button
          >
          <el-button
            style="margin-left: 20px"
            type="danger"
            size="small"
            @click="handlerDelete(index)"
            >删除</el-button
          >
        </el-col>
      </el-form>
    </el-row>
    <el-row v-if="addOK">
      <el-col :offset="8" :span="8" class="add">
        <addButton :contentText="'新增tab'" @addItem="addItem" />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { configMsg, deleteConfig } from "@/api/config";
import { onlyLetterNumberRules } from "@/utils/rules";
import { deepClone } from "@/utils/index";
import addButton from "@/components/addButton/index.vue";
export default {
  name: "tabs",
  components: {
    addButton,
  },
  props: {
    activeTabName: {
      type: String,
      default: "",
    },
  },
  data() {
    const validateType = (rule, value, callback) => {
      if (!value) {
        callback(new Error("code属性不能为空"));
      } else if (!onlyLetterNumberRules.test(value)) {
        callback(new Error("请输入合法的code属性"));
      } else {
        callback();
      }
    };
    return {
      configArr: [],
      activetab: "",
      configuration: {},
      configObj: {
        code: "",
        configuration: {},
        enable: true,
        name: "",
        type: "",
        version: 0,
      },
      rules: {
        name: [{ required: true, message: "tab名称为必填项", trigger: "blur" }],
        code: [{ required: true, validator: validateType, trigger: "blur" }],
        enable: [
          { required: true, message: "请选择是否启用", trigger: "change" },
        ],
      },
      addOK: false,
    };
  },
  methods: {
    requestConfigMsg(activeName, isSingle) {
      this.addOK = !isSingle;
      configMsg(activeName)
        .then((res) => {
          if (res.success) {
            this.configArr = res?.data ?? [];
            if (this.configArr.length > 0) {
              this.configArr.map((item) => {
                item.isonline = true; // 标记为通过后端获取的数据
              });
              this.activetab = 0;
              this.configuration = res?.data[0]?.configuration ?? {};
            } else {
              this.addItem();
              this.activetab = 0;
              this.configuration = this.configArr[0].configuration;
            }
            this.$emit("giveConfiguration", this.configuration);
          }
        })
        .catch((err) => {});
    },
    addItem() {
      switch (this.activeTabName) {
        case "Zhishu":
          this.configObj.configuration = {
            appid: "",
            appsecret: "",
            group: true,
            host: "",
            locGroup: "0",
          };
          break;
        case "Sync":
          this.configObj.configuration = {
            asset: "",
            location: "",
          };
          break;
        case "DefaultLocate":
          this.configObj.configuration = {
            statusFilter: "",
            orgFilter: "",
            maxPerShelf: "",
            group: "",
          };
          break;
        case "Reference":
          this.configObj.configuration = {
            name: "",
            logoId: "",
            url: "",
          };
          break;
        case "Feature":
          this.configObj.configuration = {};
          break;
        case "VirLib":
          this.configObj.configuration = {
            vrUrl: "",
          };
          break;
        default:
          break;
      }
      this.configObj.type = this.activeTabName;
      let newConfigObj = deepClone(this.configObj);
      this.configArr.push(newConfigObj);
      this.handlerChangeTab(this.configArr.length - 1);
    },
    handlerChangeTab(index) {
      if (index === this.activetab) {
        return;
      }
      this.activetab = index;
      this.configuration = this.configArr[index].configuration;
      this.$emit("giveConfiguration", this.configuration);
      this.$emit("clearValidateForm");
    },
    // 触发表单校验
    validateForm() {
      return new Promise((resolve) => {
        const formInstances = Array.isArray(this.$refs.form)
          ? this.$refs.form
          : [this.$refs.form];
        const validationPromises = formInstances.map((form) => {
          return new Promise((innerResolve) => {
            form.validate((valid) => {
              innerResolve(valid);
            });
          });
        });

        Promise.all(validationPromises).then((results) => {
          const allValid = results.every((result) => result);
          if (allValid) {
            const codes = this.configArr.map((item) => item.code);
            const isUnique = new Set(codes).size === codes.length;
            if (isUnique) {
              resolve(this.configArr[this.activetab]);
            } else {
              this.$message.error("code属性不能重复");
              resolve(false);
            }
          } else {
            resolve(false);
          }
        });
      });
    },
    handlerDelete(index) {
      let target = this.configArr[index];
      if (target.isonline) {
        // 线上数据删除
        let query = {
          code: target.code,
          type: target.type,
          version: target.version,
        };
        deleteConfig(query).then((res) => {
          if (res.success) {
            this.$message.success("删除成功");
            this.configArr.splice(index, 1);
          } else {
            this.$message.error("删除失败");
          }
        });
      } else {
        // 本地数据对应数组中的索引的对象删除
        this.configArr.splice(index, 1);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/index.scss";
.container {
  .tabs-item {
    width: 100%;
  }
  .btn-col {
    .el-button {
      height: 36px;
      margin: auto;
    }
  }
  .active {
    border-right: 4px solid $themeColor;
    box-sizing: border-box;
  }
  .add {
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
